//
//  QZHongBaoView.m
//  examine
//
//  Created by tikeios_002 on 2024/7/10.
//

#import "QZHongBaoView.h"
#import "QZHongBaoDetailsVC.h"
@interface QZHongBaoView ()<CAAnimationDelegate>
{
    CABasicAnimation *bas;
    NSNumber * bgtime;
}
@property (nonatomic, strong) CAShapeLayer * caShapelayer;
@property (nonatomic, assign) CFTimeInterval caShapelayerTime;
@property (nonatomic, strong) UIImageView * hongbaoImage;
@property (nonatomic, strong) UILabel * hongbaoLabel;

@end
@implementation QZHongBaoView
+ (instancetype)share {
    static QZHongBaoView *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[QZHongBaoView alloc] initWithFrame:CGRectMake(15, KNav_H+50, 50, 50)];
        
    });
    return manager;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.cornerRadius = 25;
        self.backgroundColor = ColorHex_Alpha(@"000000", 0.5);
        
        _hongbaoImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 30, 30)];
        _hongbaoImage.image = KImageNamed(@"hongbaobutie");
        [self addSubview:_hongbaoImage];
        
        _hongbaoLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 40, 40)];
        _hongbaoLabel.textColor = MainColor;
        _hongbaoLabel.font = Font(14);
        
//        _hongbaoLabel.hidden = YES;
        [self addSubview:_hongbaoLabel];
        _hongbaoLabel.textAlignment = NSTextAlignmentCenter;
        [_hongbaoLabel setTransform:CGAffineTransformMakeScale(0.1, 0.1)];
        //上半部轨迹:
        UIBezierPath * path = [UIBezierPath bezierPath];
        //圆路径
        [path addArcWithCenter:CGPointMake(25, 25) radius:25 startAngle:-0.5 * M_PI endAngle:1.5 * M_PI clockwise:YES];
        //创建一个CAShapeLayer
        _caShapelayer = [CAShapeLayer layer];
        _caShapelayer.path = path.CGPath;
        //线条宽度
        _caShapelayer.lineWidth = 2.5f;
        _caShapelayer.frame = CGRectMake(0, 0, 50, 50);
        //线条颜色
        _caShapelayer.strokeColor = MainColor.CGColor;
        //填充颜色
        _caShapelayer.fillColor = [UIColor clearColor].CGColor;
        [self.layer addSublayer:_caShapelayer];
        
        self.hongbaoStatus = YES;
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(homebaoClick)]];
        
        //监听程序进入前台和后台
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(enterBackGround)
                                                         name:UIApplicationDidEnterBackgroundNotification
                                                       object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(enterForeGround)
                                                         name:UIApplicationWillEnterForegroundNotification
                                                       object:nil];
    }
    return self;
}
- (void)enterForeGround{
//    [_caShapelayer addAnimation:bas forKey:@"key"];
    [self drawLineAnimation:_caShapelayer bgtime:0];
}
- (void)enterBackGround{
    bgtime = bas.byValue;
    [_caShapelayer removeAllAnimations];
}
- (void)setMax_time:(NSInteger)max_time{
    _max_time = max_time;
    [self drawLineAnimation:_caShapelayer bgtime:0];
    [self stopClick:NO];
}
- (void)homebaoClick{
    if([QZUserInfoModel isLogin] == NO){
        [QZUserInfoModel presentLoginView];
        return;
    }
    [QZHongBaoView share].hidden = YES;
    [[QZHongBaoView share] stopClick:NO];
    QZHongBaoDetailsVC * details = [[QZHongBaoDetailsVC alloc]init];
    [[Tools currentActiveController].navigationController pushViewController:details animated:YES];
}
//绘制 Path轨迹
- (void)drawLineAnimation:(CALayer*)layer bgtime:(CFTimeInterval)bgtime{
    bas = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    bas.duration = self.max_time;
    bas.autoreverses=NO;
    bas.delegate = self;
    bas.removedOnCompletion = NO;
    bas.fromValue = [NSNumber numberWithInteger:0];
    bas.toValue = [NSNumber numberWithInteger:1];
    [layer addAnimation:bas forKey:@"key"];
}
- (void)animationDidStart:(CAAnimation *)anim{
    NSLog(@"1");
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if(flag){
        [self watchVideoRequest];
    }
}
- (void)watchVideoRequest{
    KMutableDic(sendDic)
    sendDic[@"time"] = @(self.max_time);
    KWeakSelf
    [YBNetBase activityTaskWatchVideoRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
        if(code == 200){
            weakSelf.hongbaoImage.hidden = YES;
            weakSelf.hongbaoLabel.text = [NSString stringWithFormat:@"+%@",data[@"inc_num"]];
            weakSelf.hongbaoLabel.hidden = NO;
            KWeakSelf
            [UIView animateWithDuration:1.2 animations:^{
                [weakSelf.hongbaoLabel setTransform:CGAffineTransformMakeScale(1, 1)];
            } completion:^(BOOL finished) {
                weakSelf.hongbaoImage.hidden = NO;
                weakSelf.hongbaoLabel.hidden = YES;
                weakSelf.hongbaoLabel.transform = CGAffineTransformMakeTranslation(0, 0.1);
                [weakSelf.caShapelayer removeAllAnimations];
                [weakSelf drawLineAnimation:weakSelf.caShapelayer bgtime:0];
            }];
        }else{
            weakSelf.hongbaoImage.hidden = NO;
            weakSelf.hongbaoLabel.hidden = YES;
            weakSelf.hongbaoLabel.transform = CGAffineTransformMakeTranslation(0, 0.1);
            [weakSelf.caShapelayer removeAllAnimations];
            [weakSelf drawLineAnimation:weakSelf.caShapelayer bgtime:0];
        }
        
    }];
}

-(void)stopClick:(BOOL)isStart{
//    if(self.hongbaoStatus == isStart){
//        return;
//    }
    if([QZHongBaoView share].hongbaoStatus == isStart){
        return;
    }
    
    if(isStart == NO){
        NSLog(@"红包结束");
       
        [QZHongBaoView share].hongbaoStatus = isStart;
        CFTimeInterval bgtimes = [_caShapelayer convertTime:CACurrentMediaTime() fromLayer:nil];
        //将动画暂停
        _caShapelayer.speed = 0;
           //记录动画暂停时间
        _caShapelayer.timeOffset = bgtimes;
    }else{
        NSLog(@"红包开始");
        [QZHongBaoView share].hongbaoStatus = isStart;
        CFTimeInterval bgtimes = _caShapelayer.timeOffset;
//        if(bgtimes == 0){
//            KWeakSelf
//            [NSTimer scheduledTimerWithTimeInterval:0.4 repeats:NO block:^(NSTimer * _Nonnull timer) {
//                if([QZHongBaoView share].hongbaoStatus){
//                    [weakSelf stopClick:YES];
//                }
//            }];
//            return;
//        }
        //让动画执行
        _caShapelayer.speed = 1;
        
        //取消上次设置的时间
        _caShapelayer.beginTime = 0;
        //获取上次动画停留的时刻
        //取消上次记录的停留时刻
        _caShapelayer.timeOffset = 0;
        
        //计算暂停的时间，设置相对于父坐标系的开始时间
        _caShapelayer.beginTime = [_caShapelayer convertTime:CACurrentMediaTime() fromLayer:nil] - bgtimes;
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //NSLog(@"%s",__func__);
       //做UIView拖拽
       UITouch *touch = [touches   anyObject];
        
       //求偏移量 = 手指当前点的X -   手指上一个点的X
       CGPoint curP = [touch   locationInView:self];
       CGPoint preP =   [touch previousLocationInView:self];
       NSLog(@"curP====%@",NSStringFromCGPoint(curP));
       NSLog(@"preP====%@",NSStringFromCGPoint(preP));
        
       CGFloat offsetX = curP.x -   preP.x;
       CGFloat offsetY = curP.y -   preP.y;
        
       //平移
       self.transform = CGAffineTransformTranslate(self.transform, offsetX, offsetY);
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if(self.frame.origin.y < KNav_H){
        self.frame = CGRectMake(self.frame.origin.x, KNav_H, 50, 50);
    }
    if(self.frame.origin.y > KScreen_H-KTab_H-200){
        self.frame = CGRectMake(self.frame.origin.x, KScreen_H-KNav_H-200, 50, 50);
    }
    if(self.frame.origin.x > KScreen_W-120){
        self.frame = CGRectMake(KScreen_W-100, self.frame.origin.y, 50, 50);
    }
    
}
@end
